<template>
  <el-main>
    <h1 style="margin-bottom: 20px">{{ this.id ? '编辑广告位' : '新建广告位'}}</h1>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="名称">
            <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="广告位">
          <el-button size="small" @click="form.items.push({})"><i class="el-icon-plus"></i>添加广告</el-button>
            <el-row type="flex" style="flex-wrap: wrap;margin-top: 15px">
              <el-col :md="24" v-for="(item, i) in form.items" :key="i">
                <el-form-item label="跳转链接">
                  <el-input v-model="item.link"></el-input>
                </el-form-item>
                <el-form-item label="图片" style="margin-top: 10px">
                    <el-upload
                      class="avatar-uploader"
                      :action="uploadUrl"
                      :headers="getAuthHeaders()"
                      :show-file-list="false"
                      :on-success="res => $set(item, 'image', res.url)"
                    >
                      <img v-if="item.image" :src="item.image" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                  <el-button size="small" type="danger" @click="form.items.splice(i, 1)">删除</el-button>
                </el-form-item>
              </el-col>
            </el-row>
        </el-form-item>
        
        <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-main>
</template>
<script>
  export default {
    props: {
      id: {type: String}
    },
    data() {
      return {
        form: {
          name: '',
          items: []
        },
      }
    },
    created() {
      this.id && this.fetch()
    },
    methods: {
      async onSubmit() {
        let res
        if(this.id) {
          res = await this.$http.put(`curd/ads/${this.id}`, this.form)
        } else {
          res = await this.$http.post('curd/ads', this.form)
        }
        if(res.data.code === 200) {
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
          this.$router.push('/ads/list')
        }
      },
      async fetch() {
        const res = await this.$http.get(`curd/ads/${this.id}`)
        this.form = res.data
      },
    }
  }
</script>